package jlfm.lastfm.client.impl.simple;

import java.io.InputStream;

import jlfm.lastfm.client.TrackMetadata;
import jlfm.lastfm.client.events.LastFmClientListener;
import jlfm.lastfm.playlist.LastFmRadioPlaylist;
import jlfm.lastfm.station.LastFmStation;
import jlfm.lastfm.tools.url.LastFmCommandURL;

public class PlayListManager implements LastFmClientListener {

	private SimpleLastFmClient lastFmclient;

	private LastFmRadioPlaylist playlist = null;

	private TrackMetadata actualTrack;

	PlaylistReader reader = new PlaylistReader();

	public PlayListManager(SimpleLastFmClient simpleLastFmClient) {
		this.lastFmclient = simpleLastFmClient;
		lastFmclient.addClientListener(this);
	}

	public TrackMetadata getActualTrack() {
		return actualTrack;
	}

	public TrackMetadata getNextTrack() {
		if (playlist.size() == 0) {
			loadPlaylist();
			/*
			 * TODO Hier muss die Ausnahme behandelt werden, dass nach dem Laden
			 * einer neuen Playlist trotzdem keine weiteren Tracks mehr
			 * vorhanden sind (z.B. wenn keine weiteren Tracks in dieser Station
			 * vorhanden sind).
			 */
		}

		actualTrack = playlist.getTrackList().remove(0);
		return actualTrack;
	}

	public void loggedIn(String user, String session) {
		// TODO
		// loadPlaylist();
	}

	public void tunedIn(LastFmStation station) {
		loadPlaylist();
	}

	private void loadPlaylist() {
		playlist = reader.readPlaylist(getPlaylistInputStream());
	}

	private InputStream getPlaylistInputStream() {
		LastFmCommandURL commandUrl = new LastFmCommandURL();
		commandUrl.setFile("/radio/xspf.php");
		commandUrl.addQueryParameter("sk", lastFmclient.getSessionID());
		commandUrl.addQueryParameter("discovery", "0");
		commandUrl.addQueryParameter("desktop", "1.3.1.1");
		return lastFmclient.lastFmHttpCommandClient.getInputStream(commandUrl
				.getURL());
	}

}
